/* eslint-disable no-console */
import JsBridge from '@/utils/JsBridge.js'
import router from "@/router";
import store from "@/store/index.js";
import { showToast, showDialog } from 'vant';

/**
 * http错误处理
 */
export const errorDeal = (error) => {
  let errorText = error;
  if (errorText.toString().indexOf("timeout") > -1) {
    errorText = "请求超时";
  } else if (error.response) {
    errorText = error.response.statusText;
  } else if (error.request) {
    errorText = error.request;
  } else if (error.message) {
    errorText = error.message;
  } else if (error.msg) {
    errorText = error.msg;
  }

  if (error.apiName) {
    errorText = `${error.apiName || ""},${errorText}`;
  }

  if (error.code == 670 || error.code == 671) {
    showDialog({
      title: '登录异常',
      message: error.msg,
    }).then(() => {
      router.replace('/')
    });
  } else if (error.code == 880) {
    showDialog({
      title: '提示',
      message: `为保证你的账户安全，请您修改账户密码并重新登录`,
      closeOnPopstate: false,
    }).then(() => {
      router.replace({
        path: '/more/changePwd',
        query: {
          flag: true
        }
      })
    });
  } else if (error.code == 2000) {
    // 版本强制更新
    JsBridge.callHandler("checkUpdate", {}, (res) => {
      console.log('checkUpdate 响应值 ： ', res);
    })
  } else {
    showToast(errorText)
  }
};
export const successDeal = (text) => {
  showToast(text)
};

export const warningDeal = (text) => {
  showToast(text)
};

/**
 * @describe 获取窗口宽高
 * @param
 * @return {Object}
 **/
export const getWindowWidthAndHeight = () => {
  return {
    windowHeight:
      document.documentElement.clientHeight ||
      window.innerHeight ||
      document.body.clientHeight,
    windowWidth:
      document.documentElement.clientWidth ||
      window.innerWidth ||
      document.body.clientWidth,
  };
};
/**
 * 全局loading
 */
export const globalLoading = (off) => {
  if (off) {
    !window.GlobalLoadingTimer && (window.GlobalLoadingTimer = []);
    // 两秒内未渲染，添加loading
    window.GlobalLoadingTimer.push(
      setTimeout(() => {
        globalLoadingClear();
        store.state.loadingGlobal = true;
      }, 500)
    );
  } else {
    globalLoadingClear();
    store.state.loadingGlobal = false;
  }
};
// 清除
const globalLoadingClear = () => {
  if (window.GlobalLoadingTimer) {
    window.GlobalLoadingTimer.forEach((item) => {
      clearTimeout(item);
    });
  }
};
/**
 * 存储localStorage
 */
export const setStore = (name, content) => {
  if (!name) return;
  if (typeof content !== "string") {
    content = JSON.stringify(content);
  }
  window.localStorage.setItem(name, content);
};

/**
 * 获取localStorage
 */
export const getStore = (name) => {
  if (!name) return;
  let content = window.localStorage.getItem(name);
  return content ? JSON.parse(content) : "";
};

/**
 * 删除localStorage
 */
export const removeStore = (name) => {
  if (!name) return;
  window.localStorage.removeItem(name);
};
/**
 * 时间戳格式化
 */
export const getDateTime = function (timestamp) {
  let t = null;
  // 不传值，则获取当前时间
  if (timestamp === undefined) {
    t = new Date();
  } else if (timestamp) {
    t = new Date(parseInt(timestamp));
  }

  if (t) {
    var n = t.getFullYear();
    var a = t.getMonth() + 1;
    var r = t.getDate();
    var o = t.getHours();
    var i = t.getMinutes();
    var s = t.getSeconds();

    a >= 10 || (a = "0" + a),
      r >= 10 || (r = "0" + r),
      o >= 10 || (o = "0" + o),
      i >= 10 || (i = "0" + i),
      s >= 10 || (s = "0" + s);

    return [
      n, // yy
      a, // mm
      r, // dd
      n + "-" + a, // yy-mm
      a + "/" + r, // mm/dd
      o + ":" + i + ":" + s, // hh:mm:ss
      n + "-" + a + "-" + r + " " + o + ":" + i + ":" + s, // yy-mm-dd hh:mm::ss
      a + "-" + r + " " + o + ":" + i + ":" + s, // mm-dd hh:mm::ss
      n + "-" + a + "-" + r, // yy-mm-dd
      n + a + r, // yymmdd
      n + a, //yymm
    ];
  } else {
    return ["--", "--", "--", "--", "--", "--", "--", "--", "--"];
  }
};
/**
 * 日期转时间戳
 */
export const getUnixTime = (e) => {
  var t;
  if (e) {
    if (typeof e === "string") e = e.replace(/-/g, "/").replace(/T|Z/g, " ");
    t = new Date(e);
  } else t = new Date();
  return t.getTime();
};

/**
 * 日期转时间戳
 */
export const getTimestamp = (e) => {
  var t;
  if (e) {
    e = e.replace(/-/g, "/");
    t = new Date(e);
  } else t = new Date();
  return t.getTime().toString();
};
/**
 * 日期加上‘-’
 */
export const getJoinDate = (e) => {
  e = e.toString();
  let year = e.substring(0, 4);
  let month = e.substring(4, 6);
  let day = e.substring(6, 8);
  let date = `${year}-${month}-${day}`;
  return date;
};
/**
 * 数组去重
 */
export const unique = (arr) => {
  return Array.from(new Set(arr));
};
/**
 * 获取地址栏参数
 */
export const getUrlParam = (e, url) => {
  var t = new RegExp("(^|&)" + e + "=([^&]*)(&|$)");

  var n = url ? url.match(t) : window.location.search.substr(1).match(t);
  return n != null ? unescape(n[2]) : "";
};
/**
 * 哈希路由获取地址栏参数
 */

export const getUrlKey = (name) => {
  return (
    decodeURIComponent(
      (new RegExp("[?|&]" + name + "=" + "([^&;]+?)(&|#|;|$)").exec(
        location.href
      ) || [, ""])[1].replace(/\+/g, "%20")
    ) || null
  );
};

/**
 * 秒数格式化
 */
export const secondsFormat = (v = 0) => {
  v = parseInt(v);
  var day, minute, second, hour;
  day = Math.floor(v / (60 * 60 * 24));
  hour = Math.floor((v % (60 * 60 * 24)) / (60 * 60));
  minute = Math.floor((v % (60 * 60)) / 60);
  second = Math.floor(v % 60);
  hour < 10 && (hour = "0" + hour);
  minute < 10 && (minute = "0" + minute);
  second < 10 && (second = "0" + second);
  return day != "00"
    ? day + "天" + hour + ":" + minute + ":" + second
    : hour != "00"
      ? hour + ":" + minute + ":" + second
      : minute != "00"
        ? minute + ":" + second
        : "00:" + second;
};
/**
 * 手机格式化
 */
export const phoneFormat = (value, isNum) => {
  if (!value) return "--";
  if (isNum) {
    value = parseInt(value).toString();
  } else value = value.toString();

  let len = value.length;
  let w = value.split("");
  w.splice(3, 0, " ");
  w.splice(8, 0, " ");
  w = w.join("");
  return w;
};
/**
 * 去抖动函数
 */
export const debounce = function (wait, action) {
  let timeout;
  return function () {
    let ctx = this;
    let args = arguments;

    if (timeout) clearTimeout(timeout);

    let callNow = !timeout;
    timeout = setTimeout(() => {
      timeout = null;
    }, wait);

    if (callNow) action.apply(ctx, args);
  };
};
/**
 * iframe 文件下载
 */
export const createDownload = (url, data, cb) => {
  var body = document.getElementsByTagName("body")[0];
  var ifr = document.getElementById("downLoadForm");
  var form = document.createElement("form");
  var input = document.createElement("input");
  if (!ifr) {
    ifr = document.createElement("iframe");
    ifr.setAttribute("id", "downLoadForm");
    ifr.setAttribute("name", "downLoadForm");
    ifr.setAttribute("style", "display:none");
  }
  cb();
  ifr.addEventListener("load", function (e) {
    try {
      var res = ifr.contentWindow.document.body.textContent;
      if (res != "" && res.indexOf("code") > -1) {
        var result = JSON.parse(res);
        if (res.code != 200) {
          errorDeal(result);
        }
      }
    } catch (error) {
      errorDeal(error);
    }
  });

  form.setAttribute("style", "display:none");
  form.setAttribute("target", "downLoadForm");
  form.setAttribute(
    "enctype",
    "application/x-www-form-urlencoded;charset=utf-8"
  );
  form.setAttribute("method", "post");
  form.setAttribute("action", url);

  input.setAttribute("type", "hidden");
  input.setAttribute("name", "data");
  input.setAttribute("value", data);

  body.appendChild(ifr);
  body.appendChild(form);

  form.appendChild(input);
  form.submit();
  form.remove();
};

/* 文件流下载 */
export const BlobDownLoad = (res, name) => {
  let blob = new Blob([res.data], { type: "application/vnd.ms-excel" });
  const link = document.createElement("a");
  link.href = window.URL.createObjectURL(blob);
  link.download = name;
  link.click();
  document.body.appendChild(link);
};
/* 文件地址下载 */
export const locationDownLoad = (url) => {
  if (!url) {
    errorDeal("无下载地址");
    return false;
  }
  const link = document.createElement("a");
  link.href = url;
  link.click();
  document.body.appendChild(link);
};
/**
 * 正则验证函数
 */
export const regularValid = function (type, value) {
  let valid = false;

  switch (type) {
    case "float": // 保留后两位校验
      valid = /^[-+]?[0-9]+\.?[0-9]{0,2}$/.test(value);
      break;
    case "int+": // 正整数
      valid = /^[1-9]+$/.test(value);
      break;
    case "phone": // 手机号码校验
      valid = /^1[3-9]\d{9}$/.test(value);
      break;
    case "name": // 账户名，数字+字母+下划线组合
      valid = !/\W+/.test(value);
      break;
    case "password": // 密码校验，非法字符
      valid =
        !/[`~()|{}':;',\[\].<>/?~！￥……&*（）——|{}【】‘；：”“'。，、？]/.test(
          value
        );
      break;
    case "email": // 邮箱
      valid = /^\w+@[a-z0-9]+\.[a-z]+$/.test(value);
      break;
  }
  return valid;
};
/**
 * 正则验证函数
 */
export const passwordValid = function (str) {
  let obj = {
    valid: true,
    text: "",
  };

  let zmReg = /[A-Za-z]/; // 大小写字母
  let numReg = /[0-9]/; // 数字
  let zfReg = /[^A-Za-z0-9\s]/; // 特殊字符不包含空格
  let kgReg = /^[^\s]*$/; // 不能有空格
  let zwReg = new RegExp("[\u4E00-\u9FA5]+"); // 不能有中文
  let complex = 0;

  if (str == undefined || !str.length) {
    obj.valid = false;
    obj.text = "密码不能为空！";
    return obj;
  }

  if (!kgReg.test(str)) {
    obj.valid = false;
    obj.text = "密码不能有空格！";
    return obj;
  }

  if (zwReg.test(str)) {
    obj.valid = false;
    obj.text = "密码不能有中文！";
    return obj;
  }

  if (str.length < 6) {
    obj.valid = false;
    obj.text = "密码不能少于6位字符！";
    return obj;
  }

  if (str.length > 20) {
    obj.valid = false;
    obj.text = "密码不能多于20位字符！";
    return obj;
  }

  if (zmReg.test(str)) {
    ++complex;
  }

  if (numReg.test(str)) {
    ++complex;
  }

  if (zfReg.test(str)) {
    ++complex;
  }

  // if (complex < 2) {
  //   // 密码需包含字母，符号或者数字中至少两项且长度超过8位数，最多不超过16位数
  //   obj.valid = false
  //   obj.text = '密码必须包含字母、数字、符号中至少2种！'
  //   return obj;
  // }

  return obj;
};

/**
 * 数字格式化
 */
export const numberFormat = function (num, pro = 100) {
  return num
    ? parseFloat((parseFloat(num) / pro).toFixed(2))
      .toString()
      .replace(/\d+/, function (n) {
        return n.replace(/(\d)(?=(\d{3})+$)/g, function ($1) {
          return $1 + ",";
        });
      })
    : 0.0;
};
export const getNumberDateTime = function (value) {
  if (value) {
    var secondTime = parseInt(value); // 秒
    var minuteTime = 0; // 分
    var hourTime = 0; // 小时
    if (secondTime > 60) {
      //如果秒数大于60，将秒数转换成整数
      //获取分钟，除以60取整数，得到整数分钟
      minuteTime = parseInt(secondTime / 60);
      //获取秒数，秒数取佘，得到整数秒数
      secondTime = parseInt(secondTime % 60);
      //如果分钟大于60，将分钟转换成小时
      if (minuteTime > 60 || minuteTime == 60) {
        //获取小时，获取分钟除以60，得到整数小时
        hourTime = parseInt(minuteTime / 60);
        //获取小时后取佘的分，获取分钟除以60取佘的分
        minuteTime = parseInt(minuteTime % 60);
      }
    }
    var result = "";
    if (secondTime > 0) {
      result = "" + parseInt(secondTime) + "秒";
    }
    if (minuteTime > 0) {
      result = "" + parseInt(minuteTime) + "分" + result;
    }
    if (hourTime > 0) {
      result = "" + parseInt(hourTime) + "小时" + result;
    }
    return result;
  } else {
    return "--";
  }
};

export const bytesToSize = function (bytes, type) {
  if (bytes === 0) return "0 B";
  var k = 1024; // or 1024
  sizes = ["MB", "GB", "TB", "PB", "EB", "ZB", "YB"];
  var i = Math.floor(Math.log(bytes) / Math.log(k));

  return (bytes / Math.pow(k, i)).toPrecision(3) + " " + sizes[i];
};

//初始化时间戳(毫秒)
export const initDatepicker = function (name, time = "") {
  if (!name) return;
  let b = "";
  switch (name) {
    case 1: // 当前时间戳
      b = new Date().getTime();
      break;
    case 2: // 当天的(00时00分00秒)
      b = new Date(new Date().toLocaleDateString()).getTime();
      break;
    case 3: // 当天的(23时23分59秒)
      b =
        new Date(new Date().toLocaleDateString()).getTime() -
        999 +
        24 * 60 * 60 * 1000;
      break;

    case 4: // 自定义时间 (当天的00时00分00秒 - 时间戳)
      b = new Date(new Date().toLocaleDateString()).getTime() - time;
      break;
  }
  return b;
};

export const getExplorerInfo = function () {
  var explorer = window.navigator.userAgent.toLowerCase();
  //ie
  if (explorer.indexOf("msie") >= 0) {
    var ver = explorer.match(/msie ([\d.]+)/)[1];
    return `IE${ver}`;
  }
  //firefox
  else if (explorer.indexOf("firefox") >= 0) {
    var ver = explorer.match(/firefox\/([\d.]+)/)[1];
    return `Firefox${ver}`;
  }
  //Chrome
  else if (explorer.indexOf("chrome") >= 0) {
    var ver = explorer.match(/chrome\/([\d.]+)/)[1];
    return `Chrome${ver}`;
  }
  //Opera
  else if (explorer.indexOf("opera") >= 0) {
    var ver = explorer.match(/opera.([\d.]+)/)[1];
    return `Opera${ver}`;
  }
  //Safari
  else if (explorer.indexOf("Safari") >= 0) {
    var ver = explorer.match(/version\/([\d.]+)/)[1];
    return `Safari${ver}`;
  }
};

// 加千分号
export const toThousands = function (num, fixedNum) {
  fixedNum = fixedNum ? fixedNum : 2
  if (num) {
    return parseFloat(num).toFixed(fixedNum).replace(/(\d)(?=(\d{3})+\.)/g, '$1,');
  } else {
    return '0.00'
  }
};

// 秒转 分时天
export const formatSecToStr = function (seconds) {
  let daySec = 24 * 60 * 60;
  let hourSec = 60 * 60;
  let minuteSec = 60;
  let dd = Math.floor(seconds / daySec);
  let hh = Math.floor((seconds % daySec) / hourSec);
  let mm = Math.floor((seconds % hourSec) / minuteSec);
  let ss = seconds % minuteSec;
  if (dd > 0) {
    return dd + "天" + hh + "小时" + mm + "分钟" + ss + "秒";
  } else if (hh > 0) {
    return hh + "小时" + mm + "分钟" + ss + "秒";
  } else if (mm > 0) {
    return mm + "分钟" + ss + "秒";
  } else {
    return ss + "秒";
  }
};

//  base64转换成file对像
export const base64ToFile = function (data) {
  // 将base64 的图片转换成file对象上传 atob将ascii码解析成binary数据
  let binary = atob(data.split(",")[1]);
  let mime = data.split(",")[0].match(/:(.*?);/)[1];
  let array = [];
  for (let i = 0; i < binary.length; i++) {
    array.push(binary.charCodeAt(i));
  }
  let fileData = new Blob([new Uint8Array(array)], {
    type: mime,
  });

  let file = new File([fileData], `${new Date().getTime()}.png`, {
    type: mime,
  });

  return file;
};
